package com.qilin.hscs.hm.mqtt.handler;

import com.qilin.hscs.hm.mqtt.config.CASUtil;
import com.qilin.hscs.hm.mqtt.config.MqttClientFactory;
import com.qilin.hscs.hm.mqtt.constant.HostNameConstant;
import com.sun.istack.internal.NotNull;
import io.reactivex.Observable;
import io.reactivex.Observer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;


/**
 * Created by 10188 on 2018/3/23.
 */
@Component
public abstract class Repeater implements Observer<String>,HostNameConstant {

    private static final Logger logger= LogManager.getLogger(Repeater.class.getName());
    @Autowired
    private  RedisTemplate redisTemplate;

    protected String topicFromApp=getIEEE()+"/+";  //监听这台主机所有的二级主题命令

    protected String topicFromGateway=getIEEE()+"/+/g/rsp"; //监听这台主机所有的三级主题命令

    protected String topicToGateway;

    protected String topicVar;  //可变的主题 负责在各主机之间做参数用

    @Autowired
    protected MqttClientFactory factory;//client工厂

    @Autowired
    protected CASUtil casUtil ; //封装了发布和订阅的方法

    @Autowired
    protected LogicHandleCentry handler;

    protected Observable<String> toLogicHandler;//转发器转发消息至逻辑处理中心

    protected String msg;//需要发布和订阅的消息

    protected MqttClient clientR; //负责监听网关发布的命令

    abstract void repeat() throws MqttException;

    abstract void listenFromApp() throws  Exception;

    abstract void flushToHandler();

    @NotNull
    private String getIEEE() {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        if (jedis.exists("hostIEEE")) {
            String hostIEEE = jedis.get("hostIEEE");
            return hostIEEE;
        }else {
            logger.error("redis中无法获取到主机IEEE，请重新启动整个服务器");
        }
        return null;
    }

}
